// cas_db1_h 型号电子称对接

const regex = /\d+\.\d+/;
const decoder = new TextDecoder('utf-8');
let tempValueArray = new Uint8Array([])

let writer = null
let writerInterval = null
//外部调用
const beginMonitorReady = function () {
  if (port.writable) {
    writer = port.writable.getWriter()
    writerInterval = setInterval(async () => {
      try {
        await writer.write(new Uint8Array([5]))
        await writer.write(new Uint8Array([17]))
      } catch (e) {

      }
    }, 400)
    return true
  }
  return false
}
//外部调用
const startReader = function () {
  tempValueArray = new Uint8Array([])
}
//外部调用
const endMonitorReady = function () {
  clearInterval(writerInterval)
  try {
    writer.close();
  } catch (e) {
    console.error(e)
  }
  try {
    writer.releaseLock()
  } catch (e) {
    console.error(e)
  }
  writer = null
}
//外部调用
const valueDoWith = function (value, monitor) {
  let decodeBool = false
  let decodeValue = null

  if (value.length >= 6
    && value[0] == 1
    && value[1] == 2
    && value[value.length - 2] == 3
    && value[value.length - 1] == 4) {
    tempValueArray = value
  }
  //  有时数据会分段返回, 需要分段获取，拼接数组
  else {
    let mergedArray = new Uint8Array(tempValueArray.length + value.length);
    mergedArray.set(tempValueArray);
    mergedArray.set(value, tempValueArray.length);
    tempValueArray = mergedArray

  }

  // 符合定义的协议， exp:  1,2,83,32,32,32,48,46,52,54,107,103,99,3,4
  // console.log( tempValueArray.length, tempValueArray[0] == 1, tempValueArray[1] == 2, tempValueArray[tempValueArray.length - 2] == 3, tempValueArray[tempValueArray.length - 1] == 4 )
  if (
    tempValueArray.length >= 6
    && tempValueArray[0] == 1
    && tempValueArray[1] == 2
    && tempValueArray[tempValueArray.length - 2] == 3
    && tempValueArray[tempValueArray.length - 1] == 4) {

    let decodeStr = decoder.decode(tempValueArray.subarray(3, tempValueArray.length - 3));
    let matches = decodeStr.match(regex);
    if (matches && matches.length > 0) {
      decodeValue = matches[0]
      decodeBool = true
    }
    tempValueArray = new Uint8Array([])
  }

  monitor(decodeValue, decodeBool)

}


export default {
  beginMonitorReady, startReader,
  endMonitorReady, valueDoWith,
}

